package com.oceansoft.mobile.biz.api.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.common.util.StringUtils;
import com.oceansoft.mobile.weixin.util.RequestUtils;
import com.oceansoft.mobile.weixin.util.WeixinUtil;

/**
 * Created by zhuya on 2016/3/3.
 */
@Controller
@RequestMapping("api/hclstxz")
public class ApiHclxtxzController {
    //获取管辖大队接口
    public static String  _selOrg=Constant.host5+"api/GXDD/_selOrg";

    //货车申请接口
    public static String hclstxzReport =Constant.host5+"api/hclstxz/hcls";

    //通用申报数据推送接口
    public static String Shenbao =Constant.host5+"api/Product/Shenbao";
    //保存附件

    public static String SaveProjectMa =Constant.host5+"api/Product/SaveProjectMa";


    //车辆行驶证
    public static String cltxz ="73e0e5b8-8cbb-400f-bfbb-6dec62402d71";
    //工地工程计划
    public static String gdgcjh ="f1f755d2-d9e3-4676-bc30-4a968ff2be09";
    //证明申请理由的其他材料
    public static String qtcl ="a2993d29-a438-4ff6-b096-55c282a5a359";
    //货车通行证code
    public static String hclstxz_code ="687a63ec-7e65-41e3-b90a-7febc72dc9a4";
    //获取事项详情
    public static String getcase =Constant.host5+"api/getcase/GetDetail";
    //获取路线模板
    public static String  GetLuXianInfo=Constant.host5+"api/LuXian/GetLuXianInfo?lxname=";



    /*
    * 加载货车
    *
            * @param model
    * @return
            * @throws Exception
    */
    @RequestMapping(value = "index")
    public String hclstxz1(HttpServletRequest request,Model model)
    {
    	//System.out.println("index==============================================================");
        Map<String, String> param = new HashMap<String, String>();
        String type=request.getParameter("type");
        param.put("refid","687a63ec-7e65-41e3-b90a-7febc72dc9a4");//货车
        param.put("orgId","F1DBDF352FC94EA28A020559048718A7");
        String resp = HttpClientUtil.doPost(getcase,param,"utf-8");
        if (StringUtils.isNotBlank(resp)) {
            JSONObject respData = JSON.parseObject(resp);
            boolean succ = "true".equalsIgnoreCase(respData.getString("succ"));
            if (succ) {
                JSONObject data = new JSONObject();
                data =JSONObject.parseObject(respData.get("data").toString());
                data.put("list", data.get("baseInfo"));
                // final JSONArray data1 = respData.getJSONArray("data");
                model.addAttribute("data", data.get("baseInfo"));
                String source = (String) request.getSession().getAttribute("source");
     	       if (!StringUtils.isEmpty(source)) {
     	       	model.addAttribute("source", source);
     	       }
            }
        }
        return "weixin/matters/item_details_hc";
    }

    /*
    * 跳转货车信息
    *
            * @param model
    * @return
            * @throws Exception
    */
    @RequestMapping(value = "hclstxz2")
    public void hclstxz4(HttpSession session,HttpServletRequest request,
                             Model model)throws IllegalArgumentException, IOException {
    	//System.out.println("hclstxz2==============================================");
        Map<String, String> param = new HashMap<String, String>();
        Map<String, String> m = RequestUtils.buildParamsByNamesFromRequest(request);
//        m.put("cph","苏E"+m.get("cph"));
        param = (Map<String, String>)session.getAttribute(Constant.SESSION_HCLSTXZSQ);
        System.out.println("=================================================="+param);
        if(null==param)
        {
        	param = new HashMap<String, String>();
        }
        param.putAll(m);
       // System.out.println("=================================================="+m);
        session.removeAttribute(Constant.SESSION_HCLSTXZSQ);
        session.setAttribute(Constant.SESSION_HCLSTXZSQ,param);
    }

    /*
   * 跳转货车
   *
           * @param model
   * @return
           * @throws Exception
   */
    @ResponseBody
    @RequestMapping(value = "hclstxz3")
    public Result hclstxz5(HttpSession session,HttpServletRequest request,
                             Model model)throws IllegalArgumentException, IOException {
    	//System.out.println("hclstxz3==================================");
        Member member = (Member)session.getAttribute(Constant.SESSION_USER);
        Map<String, String> map =(Map<String, String>)session.getAttribute(Constant.SESSION_HCLS_TY);
        Map<String, String> param = new HashMap<String, String>();
        Map<String, String> m = new HashMap<String, String>();
        Result result = new Result("提交成功");
        if(null==map||StringUtils.isEmpty(map.get("projectGuid"))){
	        param = (Map<String, String>)session.getAttribute(Constant.SESSION_HCLSTXZSQ);
	        m=RequestUtils.buildParamsByNamesFromRequest(request);
	        param.putAll(m);
	        param.put("Createguid",member.getGuid());
	        result = JSONObject.parseObject((HttpClientUtil.doPost(hclstxzReport, param, "utf-8")), Result.class);
	        String guid="";
	        if(result.isSucc()){
	            guid = (String)result.getData();
	        }
	        //请空map，将通用接口信息存session
	        param.clear();
	        param.put("projectGuid",guid);
	        session.removeAttribute(Constant.SESSION_HCLSTXZSQ);
	        session.setAttribute(Constant.SESSION_HCLS_TY,param);
        }
        return result;
//        return "weixin/matters/hclstxz_03";
    }

    /*
 * 跳转货车
 *
         * @param model
 * @return
         * @throws Exception
 */
    @RequestMapping(value = "hclstxz")
    public String hclstxz2(HttpSession session,HttpServletRequest request,
                              Model model)throws IllegalArgumentException, IOException {
    	//System.out.println("hclstxz================================================");
        boolean b = WeixinUtil.checkIsLoginUser(request);
        if(!b){
            model.addAttribute("openId",request.getSession().getAttribute("openId"));
            model.addAttribute("gotoPage","/api/hclstxz/hclstxz");
            return "weixin/login/login";
        }else{
            Member member = (Member)request.getSession().getAttribute(Constant.SESSION_USER);
            model.addAttribute("data",member);
            String source = (String) request.getSession().getAttribute("source");
 	       if (!StringUtils.isEmpty(source)) {
 	       	model.addAttribute("source", source);
 	       }
            return "weixin/matters/hclstxz";
        }
    }


    /*
   * 跳转货车
   *
           * @param model
   * @return
           * @throws Exception
   */
    @RequestMapping(value = "hclstxz1")
    public void hclstxz3(HttpSession session,HttpServletRequest request,
                             Model model)throws IllegalArgumentException, IOException {
    	//System.out.println("hclstxz1=====================================");
        Map<String, String> param = new HashMap<String, String>();
        Map<String, String> m = new HashMap<String, String>();
        m=RequestUtils.buildParamsByNamesFromRequest(request);
        Member member = (Member)session.getAttribute(Constant.SESSION_USER);
        m.put("Createguid",member.getGuid());
        session.setAttribute(Constant.SESSION_HCLSTXZSQ,m);
    }
    /**
     * 获取管辖大队接口
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "_selOrg", method = GET)
    public Result Sglxmb(Model model) throws IllegalArgumentException, IOException {
        //System.out.println(_selOrg);
        String resp = HttpClientUtil.doGet(_selOrg);
        Result result = new Result();
        if (StringUtils.isNotBlank(resp)) {
            JSONObject respData = JSON.parseObject(resp);
            boolean succ = "true".equalsIgnoreCase(respData.getString("succ"));
            if (succ) {
                JSONObject data = new JSONObject();
                data.put("list", respData.getJSONArray("data"));
                final JSONArray data1 = respData.getJSONArray("data");
                model.addAttribute("data",data1);
                result.setData(data1);
            }
        }
        return result;
    }
    /**
     * 申报
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "report", method = GET)
    public Result submithclstxz(HttpSession session,HttpServletRequest request) throws IllegalArgumentException, IOException {
    	//System.out.println("report==================================================================");
    	String url = Constant.host5 + "api/Product/Shenbao";
        Map<String, String> param = new HashMap<String, String>();
        param = (Map<String, String>) session.getAttribute(Constant.SESSION_HCLS_TY);
        //附件Id
        Map<String ,Result> m = (Map<String ,Result>)session.getAttribute("hclx_fj");
        session.removeAttribute(Constant.SESSION_HCLS_TY);
        session.removeAttribute("hclx_fj");
        Member member = (Member)session.getAttribute(Constant.SESSION_USER);
        if(null==m||m.isEmpty())
        {
            return new Result(false);
        }
        String fjguid ="";
        String caseMatGuid = "";
        //循环读取附件
        Set<String> fjkeys = m.keySet();
        for (String key : fjkeys) {
            Result r = m.get(key);
            fjguid+= ((JSONObject)r.getData()).get("prjMatGuid")+";";
            caseMatGuid+= ((JSONObject)r.getData()).get("caseMatGuid")+";";
        }
        param.put("fjguid",fjguid);
        param.put("caseMatGuid",caseMatGuid);
        param.put("declareCaseGuid",hclstxz_code);
        //附加用户信息
        RequestUtils.putUser(request, param);
        Result rst = JSONObject.parseObject(HttpClientUtil.doPost(url, param, "utf-8"), Result.class);
        //System.out.println("++++++"+rst.getData());
        return rst;
    }

    /**
     *货车图片上传2
     * @param base64
     * @return
     */
    @ResponseBody
    @RequestMapping(value="uploadMsg",method= RequestMethod.POST)
    public Result uploadMsg(HttpServletRequest request){
    	String type=request.getParameter("type");
		String seesionname = request.getParameter("imgname");
		String base64 = request.getParameter("base64");
		String name=request.getParameter("name");
		if(base64==""||base64==null){
			System.out.println("======type:"+type+";seesionname是:"+ seesionname+";base64是,"+ base64+";name是:"+name);
			return new Result(Result.FAILURE);
		}
        //type字段用于识别前台传过来的不同图片
        String caseMatGuid = "";
        if("1".equals(type)){
            caseMatGuid=cltxz;//,qtcl
        }else if("2".equals(type)){
            caseMatGuid=gdgcjh;//gdgcjh,
        }else if("3".equals(type)){
            caseMatGuid=qtcl;//gdgcjh,qtcl
        }
        Result result =  RequestUtils.saveFj(request,base64,caseMatGuid, true);
        //Result result =new Result();
        Map<String ,Result> m = (Map<String , Result>)request.getSession().getAttribute(name);
        request.getSession().removeAttribute(name);
        if(null==m) 
        {
            m = new HashMap<String ,Result>();
        }
        m.put(seesionname,result);
//        System.out.println("货车附件信息==="+m.size()+"   "+m.toString());
        request.getSession().setAttribute(name,m);
        return result;
    }
    /**
     * 获取路线接口
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "GetLuXianInfo")
    public Result GetLuXianInfo(HttpServletRequest request) throws IllegalArgumentException, IOException {
        String name = request.getParameter("name");
        String url = GetLuXianInfo+name;
        //String resp = HttpClientUtil.doGet(url);
        Result result =JSONObject.parseObject( HttpClientUtil.doGet(url), Result.class);
        return result;
    }

}
